import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    component: () => import('@/views/login/IndexPage')
  },
  {
    path: '/',
    component: () => import('@/views/layout/IndexPage'),
    redirect: '/dashboard',
    children: [
      { path: '/article', component: () => import('@/views/article/IndexPage') },
      { path: '/dashboard', component: () => import('@/views/dashboard/IndexPage') }
    ]
  }
]

const router = new VueRouter({
  routes
})

const writeList = ['/login']
router.beforeEach((to, from, next) => {
  // 获取token
  const userInfo = JSON.parse(localStorage.getItem('userInfo'))
  // 校验是否登录
  if (userInfo?.token) {
    return next()
  }

  // 是否在白名单中
  if (writeList.includes(to.path)) {
    return next()
  }

  // 跳转到登录页
  next('/login')
})

export default router
